package com.example.service;

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

@Service
public class CoverService {
    private final String UPLOAD_DIR = "uploads/covers/";
    private final String[] COLORS = {
        "#FF6B6B", "#4ECDC4", "#45B7D1", "#96CEB4", "#FFEEAD",
        "#D4A5A5", "#9B9B9B", "#A8E6CF", "#FFD3B6", "#FF8B94"
    };

    public CoverService() {
        createUploadDirectory();
    }

    private void createUploadDirectory() {
        File directory = new File(UPLOAD_DIR);
        if (!directory.exists()) {
            directory.mkdirs();
        }
    }

    public String uploadCover(MultipartFile file) throws IOException {
        if (file != null && !file.isEmpty()) {
            String fileName = UUID.randomUUID().toString() + "_" + file.getOriginalFilename();
            Path path = Paths.get(UPLOAD_DIR + fileName);
            Files.write(path, file.getBytes());
            return "/" + UPLOAD_DIR + fileName;
        }
        return generateRandomCover();
    }

    public String generateRandomCover() {
        String color = COLORS[(int) (Math.random() * COLORS.length)];
        return String.format("https://via.placeholder.com/200x300/%s/FFFFFF?text=Book+Cover",
                color.substring(1));
    }
} 